package com.linewell.mobile.controller;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import com.linewell.commom.model.FeedBack;
import com.linewell.commom.model.SecondMarket;
import com.linewell.system.model.SysCustomer;
import com.linewell.system.model.SysNotice;
import com.linewell.system.pagemodel.ReturnInfo;
import com.linewell.system.service.ISysCustomerService;
import com.linewell.system.utils.ConfigProperty;
import com.linewell.system.utils.FileUploadUtil;
import com.linewell.system.utils.MD5;



/**
 * 操作前端首页的控制器
 * 
 * @author linzhiwei
 * @Data 2016/10/18
 */
@Controller
@EnableWebMvc
@SuppressWarnings("unchecked")
@RequestMapping(value="/mobile")
public class MobileMainController extends MobileBaseController {
	
	private static final Log log = LogFactory.getLog(MobileMainController.class);
	@Autowired
	private ISysCustomerService sysCustomerService;
	/**
	 * 登录
	 */
	@ResponseBody
	@RequestMapping(value = "/doLogin")
	public ReturnInfo doLogin(String custName, String password, ReturnInfo info, HttpServletRequest request) {
 
		if (custName != null && custName != null) {
			password = MD5.md5(password); // MD5加密登录密码
			//将登录用户信息存入session
			HttpSession session = request.getSession();
			session.setAttribute("CustName", custName);
		 Object b = session.getAttribute("CustName");
			String hql = " from SysCustomer t where t.custName ='" + custName + "' ";
			Query query = super.sessionFactory.getCurrentSession().createQuery(hql);
		}else {
				info.setSuccess(1);
				info.setMsg("用户名或密码错误!");
			}
		
		return info;
	}
	/**
	 * 进入前端登录页面
	 */
	@RequestMapping(value = "/index")
	public String index() {
		return "/WEB-INF/pages/mobile/login/login.jsp";
	}
	/**
	 * 进入前端登录页面
	 */
	@RequestMapping(value = "/success")
	public String success() {
		return "/WEB-INF/pages/mobile/login/success.jsp";
	}
	/**
	 * 进入前端注册页面
	 */
	@RequestMapping(value = "/register")
	public String register(Map<String, Object> map) {
		map.put("saveUrl", "/mobile/registerSuccess");
		return "/WEB-INF/pages/mobile/login/register.jsp";
	}
	/**
	 * 注册
	 */
	@ResponseBody
	@RequestMapping(value = "/registerSuccess")
	public ReturnInfo addSave(String password,@Valid SysCustomer sysCustomer, BindingResult b, ReturnInfo result, @RequestParam(value = "uploadFile", required = false) MultipartFile file, HttpServletRequest request) {
		if (b.getErrorCount() > 0) { // 数据校验
			for (FieldError error : b.getFieldErrors()) {
				log.info(error.getField() + ":" + error.getDefaultMessage());
				result.setMsg(error.getField() + "" + error.getDefaultMessage());
			}
			result.setSuccess(1);
		} else {
			if(password != null){
				password=MD5.md5(password);
			}else{
				password=MD5.md5("123456");
			}
			if (sysCustomer != null) {
				if(file != null){
					try {
						String icon_url = FileUploadUtil.saveFile(file, request, ConfigProperty.getProperty("fileUplaodPath", "config") + "photo");
						sysCustomer.setPhoto(icon_url);
					} catch (Exception e) {
						log.info("上传异常"+e.getMessage());
					}
				}
				try {
					sysCustomer.setPassword(password);
					sysCustomerService.save(sysCustomer);
				} catch (Exception e) {
					result.setMsg("保存失败！");
					result.setSuccess(1);
				}
			}
		}
		return result;
	}
	/**
	 * 进入前台首页
	 */
	@RequestMapping(value = "/")
	public String index(HttpServletRequest request) {
		return super.index("/WEB-INF/pages/mobile/main/main.jsp", request);
		
	}
	/**
	 * 获得部分商品和系统公告，用于显示推荐商品
	 */
	@ResponseBody
	@RequestMapping(value = "/getCommodity")
	public ReturnInfo getCommodity(ReturnInfo info) {

		List<SecondMarket> lstAll = null;

		try {
			String hql = " from  SecondMarket v where v.status = 9  order by createTime desc";
			lstAll = super.find(hql, 1, 8);
			info.setObj(lstAll);
		} catch (Exception e) {
			log.info("异常" + e.getMessage());
		}

		List<SysNotice> lstAll2 = null;

		try {
			String hql = " from  SysNotice o where o.status = 9 order by pubTime desc ";
			lstAll2 = super.find(hql, 1, 10);
			info.setRows(lstAll2);
		} catch (Exception e) {
			log.info("异常" + e.getMessage());
		}

		return info;
	}

	/**
	 * 进入前端商品详情页
	 */
	@RequestMapping(value = "/commoditySkip")
	public String commoditySkip(Integer id, Map<String, Integer> map, HttpServletRequest request) {
		map.put("id", id);
		return super.index("/WEB-INF/pages/mobile/market/market_info.jsp", request);
	}

	/**
	 * 根据id获得单个商品的详细信息
	 * 
	 * @parameter id
	 * @return list
	 */
	@ResponseBody
	@RequestMapping(value = "/getComDetail")
	public ReturnInfo getComDetail(Integer id, ReturnInfo info) {

		if (id != null && !"".equals(id)) {

			List<SecondMarket> lstAll = null;

			try {
				String hql = " from  SecondMarket o where o.status = 9 and o.marketId = " + id + " ";
				lstAll = super.find(hql);
				info.setObj(lstAll);
			} catch (Exception e) {
				log.info("异常" + e.getMessage());
			}

		}
		return info;
	}

	/**
	 * 关于我们
	 */
	@RequestMapping(value = "/about")
	public String aboutUs(HttpServletRequest request) {
		return super.index("/WEB-INF/pages/mobile/main/about.jsp", request);
	}

	/**
	 * 进入前端帮助页
	 */
	@RequestMapping(value = "/help")
	public String heleMe(HttpServletRequest request) {
		return super.index("/WEB-INF/pages/mobile/main/help.jsp", request);
	}
	
	/**
	 * 用户提交反馈
	 * 
	 * @parameter
	 * @return list
	 */
	@ResponseBody
	@RequestMapping(value = "/feedBack")
	public ReturnInfo feedBack(String content, String phone, ReturnInfo info, HttpServletRequest request) {
		if (content != null && !"".equals(content) && phone != null && !"".equals(phone)) {
			try {
				content = java.net.URLDecoder.decode(content, "UTF-8");
				StringBuffer hql = new StringBuffer();
				hql.append("insert into feed_back(CONTENT,PHONE) values('" + content + "','" + phone + "') ");
				Query query = super.sessionFactory.getCurrentSession().createSQLQuery(hql.toString());
				query.executeUpdate();

			} catch (Exception e) {
				log.info("异常" + e.getMessage());
				info.setSuccess(1);
			}

		} else {
			info.setSuccess(1);
			info.setMsg("请填写完整信息！");
		}
		return info;
	}
	/**
	 * 进入前端帮助页
	 */
	@RequestMapping(value = "/feek")
	public String feek(HttpServletRequest request) {
		return super.index("/WEB-INF/pages/mobile/main/feedback.jsp", request);
	}
	/**
	 * 搜索商品
	 * 
	 * @parameter page 当前页 rows 每页显示记录数
	 * @return list
	 */
	@ResponseBody
	@RequestMapping(value = "/searchComm")
	public ReturnInfo searchComm(ReturnInfo info, String content, Integer page, Integer rows) {
		if (content != null && !"".equals(content)) {
			try {
				content = java.net.URLDecoder.decode(content, "UTF-8");
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
			List<SecondMarket> lstAll = null;
			try {
				String hql = " from  SecondMarket v where v.summary like '%" + content
						+ "%' and  v.status = 9  order by createTime desc ";
				lstAll = super.find(hql, page, rows);
				info.setRows(super.count("select count(*) " + hql)); // 总记录数
				info.setObj(lstAll);
			} catch (Exception e) {
				info.setSuccess(1);
				log.info("异常" + e.getMessage());
			}
		} else {
			info.setSuccess(1);
			info.setMsg("提交失败！");
		}
		return info;
	}
	/**
	 * 进入商品页面
	 */
	@RequestMapping(value = "/market")
	public String market(HttpServletRequest request) {
		return super.index("/WEB-INF/pages/mobile/market/second_market.jsp", request);
	}
	
	@ResponseBody
	@RequestMapping(value = "/getComInfo")
	public ReturnInfo getCommodity(ReturnInfo info, Integer page, Integer rows) {
		
		if (page != null && rows != null) {
		List<SecondMarket> lstAll = null;

		try {
			String hql = " from  SecondMarket o where o.status = 9 order by createTime desc  ";
			lstAll = super.find(hql, page, rows);
			info.setRows(super.count("select count(*) " + hql)); // 总记录数
			info.setObj(lstAll);
		} catch (Exception e) {
			log.info("异常" + e.getMessage());
			}
		}
		return info;
	}
}
